<?php 
namespace Member\Controller;

use Member\ORG\Wechat;
class UserController extends ManageController {
	/**
	 * 关注用户列表
	 */
	function index($appid) {
		$map['appid'] = $appid;
		$list = $this->lists('User', $map);
		$this->assign('__LIST__', $list);
		$this->title('用户列表');
		$this->display();
	}
	
	/**
	 * 刷新关注列表
	 */
	function subscribe_list($appid) {
		$wechat = new Wechat($appid);
		$listNew = $wechat->users();
		$model = M('User');
		$listOld = $model->where('appid='.$appid)->getField('openid', true);
		if (empty($listOld)) {
			$list = $listNew;
		}else {
			$list = array_diff($listNew, $listOld);
		}
		if (empty($list)) $this->error('无新增用户！');
		foreach ($list as $k=>$v) {
			$data[$k] = $wechat->user($v);
			$data[$k]['appid'] = $appid;
		}
		sort($data);
		if ($model->addAll($data)) {
			$this->success('刷新用户列表成功！');
		}else {
			$this->error('刷新列表失败！');
		}
	}
	
	/**
	 * 刷新用户信息
	 */
	function refresh($appid, $uid) {
		$model = M('User');
		$userInfo = $model->find($uid);
		$wechat = new Wechat($appid);
		$data = $wechat->user($userInfo['openid']);
		if (!$data) {
			$this->error('获取用户信息失败！');
		}
		$model->where('id='.$uid)->save($data);
		$this->success('刷新用户信息成功！');
	}
	
	/**
	 * 用户留言
	 */
	function guestbook($appid) {
		$map['appid'] = $appid;
		$list = $this->lists('Guestbook', $map);
		$this->assign('__LIST__', $list);
		$this->title('用户留言');
		$this->display();
	}

	/**
	 * 回复留言
	 */
	function sendmsg($appid, $uid, $msgid) {
		if (IS_POST) {
			$openid = I('post.openid');
			$content = I('post.content');
			$wechat = new Wechat($appid);
			$res = $wechat->send($openid, $content);
			if ($res) {
				$this->success('发送成功！');
			}else {
				$this->error($wechat->getError());
			}
		}else {
			$map['openid'] = $uid;
			$info = M('User')->where($map)->find();
			$this->assign('info', $info);
			$this->assign('content', M('Guestbook')->where('id='.$msgid)->getField('content'));
			
			$this->title('回复留言');
			$this->display();
		}
	}
	
	function look($appid, $msgid) {
		$this->assign('content', M('Guestbook')->where('id='.$msgid)->getField('content'));
		$this->display();
	}
}